/**
 * 
 */
package org.ztest.file;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

/**
 * @author lhl
 *
 * 2015年7月31日上午9:37:58
 */
public class FileWatcher implements Runnable
{
	private WatchService watchService;
	private WatchKey watchKey;
	
	public FileWatcher(String directory) throws IOException, InterruptedException
	{
		register(directory);
	}
	
	public void register(String directory) throws IOException, InterruptedException
	{
		Path faxFolder = Paths.get(directory);
		watchService = FileSystems.getDefault().newWatchService();
		faxFolder.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
		watchKey = watchService.take();
	}

	@Override
	public void run()
	{
		boolean valid = true;
		do
		{
			for (WatchEvent<?> event : watchKey.pollEvents())
			{
				Kind<?> kind = event.kind();
				if (StandardWatchEventKinds.ENTRY_MODIFY.equals(kind))
				{
					String fileName = event.context().toString();
					System.err.println(fileName + " changed!");
				}
				valid = watchKey.reset();
			}
		}
		while (valid);
	}
}
